package com.ydd.service.impl;

import com.ydd.context.BaseStringContext;
import com.ydd.dto.LoginAndRegDTO;
import com.ydd.entity.*;
import com.ydd.mapper.*;
import com.ydd.service.AdminIndexService;
import com.ydd.vo.*;
import com.ydd.vo.common.AllCate;
import com.ydd.vo.common.DictsType;
import com.ydd.vo.common.SysUserInfo;
import com.ydd.vo.common.UserTotal;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.*;

/**
 * @Description TODO
 * @Author fang
 * @Date 2023-05-29 16:13
 */
@Service
public class AdminIndexServiceImpl implements AdminIndexService {

    @Autowired
    YddAdvposMapper yddAdvposMapper;
    @Autowired
    YddTagMapper yddTagMapper;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    YddArticleMapper yddArticleMapper;
    @Autowired
    YddCateMapper yddCateMapper;
    @Autowired
    YddAdvimgMapper yddAdvimgMapper;
    @Autowired
    YddUserMapper yddUserMapper;
    @Autowired
    SysRoleMapper sysRoleMapper;
    @Autowired
    SysMenuMapper sysMenuMapper;
    @Autowired
    SysRoleMenuMapper sysRoleMenuMapper;
    @Autowired
    SysDictMapper sysDictMapper;
    @Autowired
    SysConfigMapper sysConfigMapper;

    /**
     * 基础模块-主页统计信息
     * @return
     */
    @Override
    public IndexBaseInfoVO baseInfo() {
        Integer yddAdvposNum = yddAdvposMapper.getYddAdvposNum();
        Integer tagNum = yddTagMapper.getTagNum();
        Integer adminNum = sysUserMapper.getAdminNum();
        Integer articleNum = yddArticleMapper.getArticleNum();
        Integer cateNum = yddCateMapper.getCateNum();
        Integer advimgNum = yddAdvimgMapper.getAdvimgNum();

        List<YddUser> newUsers = yddUserMapper.getNewUsers();
        List<UserVO> new_user = new ArrayList<>();
        newUsers.forEach(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            new_user.add(userVO);
        });

        List<YddCate> yddCates = yddCateMapper.getAllCate();
        List<AllCate> all_cate = new ArrayList<>();
        yddCates.forEach(yddCate -> {
            Integer num = yddArticleMapper.countByCateId(yddCate.getId());
            AllCate cate = AllCate.builder()
                    .id(yddCate.getId())
                    .catename(yddCate.getCatename())
                    .num(num).build();
            all_cate.add(cate);
        });

        List<YddArticle> hotArticle = yddArticleMapper.getHotArticle();
        List<ArticleVO> hot_article = new ArrayList<>();
        hotArticle.forEach(article -> {
            ArticleVO articleVO = new ArticleVO();
            BeanUtils.copyProperties(article, articleVO);
            articleVO.setCreate_date(article.getCreateDate());
            articleVO.setUpdate_date(article.getUpdateDate());
            hot_article.add(articleVO);
        });

        Integer total = yddUserMapper.getNumBySex(null);
        Integer man = yddUserMapper.getNumBySex(0);
        Integer woman = yddUserMapper.getNumBySex(1);
        UserTotal userTotal = UserTotal.builder()
                .total(total)
                .user_man(man)
                .user_woman(woman).build();

        IndexBaseInfoVO indexBaseInfoVO = IndexBaseInfoVO.builder()
                .all_cate(all_cate)
                .advpos_num(yddAdvposNum)
                .tag_num(tagNum)
                .admin_num(adminNum)
                .article_num(articleNum)
                .cate_num(cateNum)
                .advimg_num(advimgNum)
                .new_user(new_user)
                .user(userTotal)
                .hot_article(hot_article).build();

        return indexBaseInfoVO;
    }

    /**
     * 基础模块-获取用户资料
     *
     * @return
     */
    @Override
    public IndexProfileVO profile() {
        //userInfo
        SysUserInfo sysUserInfo = new SysUserInfo();
        SysUser sysUser = sysUserMapper.getById(BaseStringContext.getCurrentId());
        BeanUtils.copyProperties(sysUser, sysUserInfo);
        sysUserInfo.setLogin_name(sysUser.getLogin_name());
        sysUserInfo.setLogin_ip(sysUser.getLoginIp());
        sysUserInfo.setCreate_date(sysUser.getCreateDate());
        sysUserInfo.setUpdate_date(sysUser.getUpdateDate());
        sysUserInfo.setDel_flag(sysUser.getDelFlag());
        sysUserInfo.setDefault_data(sysUser.getDefaultData());

        String roleIdStr = sysUser.getRoleId();
        String[] roleIds = roleIdStr.replaceAll("[\\[\\]\"]","").split(",");
        List<String> role_id = Arrays.asList(roleIds);
        sysUserInfo.setRole_id(role_id);

        boolean flag = false;
        List<String> rolename = new ArrayList<>();
        for (String roleId : role_id) {
            SysRole sysRole = sysRoleMapper.getRoleById(roleId);
            rolename.add(sysRole.getName());
            if (sysRole.getSuperadmin() == 1) {
                flag = true;
            }
        }
        sysUserInfo.setRolename(rolename);


        //menuList + btnList（如果菜单出不来，检查一下SysMenu和MenuVO的属性类型）
        Map<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("roleIdList", role_id);
        conditionMap.put("type", 1);
        List<SysMenu> sysMenuList = sysMenuMapper.getByCondition(conditionMap);
        List<MenuVO> menuList = new ArrayList<>();
        for (SysMenu sysMenu : sysMenuList) {
            MenuVO menuVO = new MenuVO();
            BeanUtils.copyProperties(sysMenu, menuVO);
            menuVO.setIs_show(sysMenu.getIsShow());
            menuVO.setIs_cache(sysMenu.getIsCache());
            menuVO.setIs_link(sysMenu.getIsLink());
            menuVO.setCreate_date(sysMenu.getCreateDate());
            menuVO.setUpdate_date(sysMenu.getUpdateDate());
            menuVO.setDel_flag(sysMenu.getDelFlag());
            menuVO.setDefault_data(sysMenu.getDefaultData());
            menuList.add(menuVO);
        }

        List<MenuVO> btnList = null;
        if (!flag) {
            conditionMap.put("type", 2);
            List<SysMenu> sysBtnList = sysMenuMapper.getByCondition(conditionMap);
            btnList = new ArrayList<>();
            for (SysMenu sysMenu : sysBtnList) {
                MenuVO menuVO = new MenuVO();
                BeanUtils.copyProperties(sysMenu, menuVO);
                menuVO.setIs_show(sysMenu.getIsShow());
                menuVO.setIs_cache(sysMenu.getIsCache());
                menuVO.setIs_link(sysMenu.getIsLink());
                menuVO.setCreate_date(sysMenu.getCreateDate());
                menuVO.setUpdate_date(sysMenu.getUpdateDate());
                menuVO.setDel_flag(sysMenu.getDelFlag());
                menuVO.setDefault_data(sysMenu.getDefaultData());
                btnList.add(menuVO);
            }
        }

        //dictsList
        Map<String,String> interface_type =new HashMap<>();
        Map<String,String> order_type  =new HashMap<>();
        Map<String,String> report_type =new HashMap<>();
        Map<String,String> table_type  =new HashMap<>();
        Map<String,String> theme =new HashMap<>();
        List<SysDict> sysDictList = sysDictMapper.getAllDictData();
        for (SysDict sysDict : sysDictList) {
            if (sysDict.getType().equals("interface_type")) {
                interface_type.put(sysDict.getValue(),sysDict.getLabel());
            }
            if (sysDict.getType().equals("order_type")) {
                order_type.put(sysDict.getValue(),sysDict.getLabel());
            }
            if (sysDict.getType().equals("report_type")) {
                report_type.put(sysDict.getValue(),sysDict.getLabel());
            }
            if (sysDict.getType().equals("table_type")) {
                table_type.put(sysDict.getValue(),sysDict.getLabel());
            }
            if (sysDict.getType().equals("theme")) {
                theme.put(sysDict.getValue(),sysDict.getLabel());
            }
        }
        DictsType dictsType = DictsType.builder()
                .interface_type(interface_type)
                .order_type(order_type)
                .report_type(report_type)
                .table_type(table_type)
                .theme(theme).build();

        //封装数据
        if (!flag) {
            IndexProfileVO<MenuVO> indexProfileVO = new IndexProfileVO<>();
            indexProfileVO.setBtnList(btnList);
            indexProfileVO.setUserInfo(sysUserInfo);
            indexProfileVO.setMenuList(menuList);
            indexProfileVO.setDictsList(dictsType);
            return indexProfileVO;
        } else {
            IndexProfileVO<String> indexProfileVO = new IndexProfileVO<>();
            List<String> list = new ArrayList<>();
            list.add("*");
            indexProfileVO.setBtnList(list);
            indexProfileVO.setUserInfo(sysUserInfo);
            indexProfileVO.setMenuList(menuList);
            indexProfileVO.setDictsList(dictsType);
            return indexProfileVO;
        }

    }



    /**
     * 基础模块-获取系统配置
     * @return
     */
    @Override
    public IndexGetConfigVO getConfig() {
        ArrayList<String> list = sysConfigMapper.getConfig();
        System.out.println(list);
        IndexGetConfigVO indexGetConfigVO = new IndexGetConfigVO();
        indexGetConfigVO.setLogin_title(list.get(0));
        indexGetConfigVO.setLogin_bg(list.get(1));
        indexGetConfigVO.setSystem_name(list.get(2));
        indexGetConfigVO.setSystem_logo(list.get(3));
        indexGetConfigVO.setWeb_ico(list.get(4));
        return indexGetConfigVO;
    }

    /**
     * 基础模块-登陆相关方法
     * @param loginAndRegDTO
     * @return
     */
    @Override
    public SysUser findByCondition(LoginAndRegDTO loginAndRegDTO) {
        String md5 = DigestUtils.md5DigestAsHex((loginAndRegDTO.getPassword()).getBytes());
        loginAndRegDTO.setPassword(md5);
        SysUser sysUser = sysUserMapper.findByCondition(loginAndRegDTO);
        return sysUser;
    }
}
